package com.edu.zut.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author 许文科
 * @Date 2023/1/12 17:26
 * @Description paperdetect-bcak
 */
public class JwtUtil {

    //过期时间是1小时
    private static final long EXPIRE_TIME = 36000000;
    private static final String ISSER = "auth0";
    //加密盐
    private static final String SECRET = "paper-detect";
    //验证token合法性
    public final static JWTVerifier VERIFIER = JWT.require(Algorithm.HMAC256(SECRET)).withIssuer(ISSER).build();

    /**
     * 生成签名 返回token
     * 将学号/工号，和角色封装到token中
     *
     * @param userName
     * @param roleNames
     * @return
     */
    public static String sign(String userName, List<String> roleNames) {

        String token = null;
        //从当前系统时间到过期时间
        Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);

        token = JWT.create()
                .withIssuer(ISSER)
                .withClaim("userName", userName)
                .withClaim("roleNames", JSON.toJSONString(roleNames))
                .withExpiresAt(expiresAt)
                //使用HMAC256加密算法
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 验签，验证token合法性
     *
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            VERIFIER.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 解析token,取出token中的值
     *
     * @param token
     * @return
     */
    public static Map<String, Claim> getClaimsFormToken(String token) {
        try {
            DecodedJWT jwt = VERIFIER.verify(token);
            return jwt.getClaims();
        } catch (Exception e) {
            return null;
        }
    }


}
